// by Xeno
#define THIS_FILE "fn_spawn_trench.sqf"
#include <core_macros.h>

private ["_pos", "_dir", "_trenchtype", "_trench"];

if (PGETVAR(GVAR(isinaction),false)) exitWith {
	GVAR(commandingMenuIniting) = false;
};

if (((getPos player) select 2) > 5) exitWith {
	systemChat (localize "STR_XS_TRENCHTOOHIGH");
	GVAR(commandingMenuIniting) = false;
};

_pos = player modeltoworld [0,1,0];
// TYRGHEN - putting the item a bit inside the ground to make it smaller
_pos set [2, -0.4];
_dir = direction player;

if (surfaceIsWater _pos) exitWith {
	systemChat (localize "STR_XS_TRENCHWATER");
	GVAR(commandingMenuIniting) = false;
};

if (isOnRoad _pos) exitWith {
	systemChat (localize "STR_XS_TRENCHROAD");
	GVAR(commandingMenuIniting) = false;
};

PSETVAR(QGVAR(isinaction), true);

systemChat (localize "STR_XS_BUILDINGTRENCH");

// TYRGHEN - added a global variable
if (isNil QGVAR(trench_type)) then { GVAR(trench_type) = "Land_BagFence_Short_F" };
_trenchtype = GVAR(trench_type);

player playMove "AinvPknlMstpSlayWrflDnon_medic";
sleep 3;
waitUntil {animationState player != "AinvPknlMstpSlayWrflDnon_medic"};
GVAR(commandingMenuIniting) = false;
if (!alive player) exitWith {
	systemChat (localize "STR_XS_DIEDBEFOREDONE");
	PSETVAR(QGVAR(isinaction), false);
};

_trench = createVehicle [_trenchtype, _pos, [], 0, "NONE"];
_trench setdir _dir;
_trench setPos _pos;

PSETVAR(QGVAR(isinaction), false);
systemChat (localize "STR_XS_TRENCHDONE");
_trench spawn {
	waituntil { sleep 12.3456; (!alive _this) || (_this distance player) > 200 || (!alive player) };
	if (!isnull _this) then {
		deleteVehicle _this;
	};
};